<template>
    <div style="border: 1px solid #ccc" class="notice">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :default-config="toolbarConfig"
        :mode="mode"
      />
      <Editor
        v-model="html"
        style="height: 500px; overflow-y: hidden"
        :default-config="editorConfig"
        :mode="mode"
        @onChange="onChange"
        @onCreated="onCreated"
      />
    </div>
  </template>
  <script>
  import Vue from "vue";
  import axios from "axios";
  import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
//   import { upload } from "@/api/guideCertificate/guideCertificateIndex";
//   import { getToken } from "@/utils/auth";
  import {  Message } from "element-ui";
  import { DomEditor } from '@wangeditor/editor'
  const editorConfig = {
    // JS 语法
    MENU_CONF: {},
    placeholder: "请输入内容...",
   
    // 其他属性...
  };
  // 自定义上传图片
  editorConfig.MENU_CONF['uploadImage'] = {
        customUpload(file, insertFn) {
          const fileName = file.name
          const m = fileName.match(/\.(\w+)(#|\?|$)/)
          const fileType = (m && m[1]).toString().toLowerCase()
          const allowHook = ["bmp", "png", "jpg", "jpeg", "gif"]
          const validType = (allowHook).includes(fileType)
          if (!validType) {
            Message.error('只支持图片类型文件上传')
            return false
          }
          if (fileName.indexOf('%') > -1 || fileName.indexOf('&') > -1) {
            Message.error('上传文件名称不能带有字符"%","&"')
            return false
          }
          const isLt5M = file.size / 1024 / 1024 < 5
          if (!isLt5M) {
            Message.error('上传图片大小不能超过 5MB!')
            return false
          }
          if (["bmp", "png", "jpg", "jpeg", "gif"].includes(fileType)) {
            var formData = new FormData();
            formData.set('file', file)
            var API = process.env.VUE_APP_BASE_API + "/common/v1/upload";
            axios.post(API, formData).then(fileUrl => {
                  // console.log('fileUrl',fileUrl)
                  let url = fileUrl.data.result.url
                  let alt = file.name
                  let href = fileUrl.data.result.url
                  insertFn(url, alt, href)
            }).catch(error => {
              Message.error(error.message);
            })
          }
        }
      }
 
  editorConfig.MENU_CONF["uploadVideo"] = {
    server: "/concatenation/dzznInfo/upload",
    fieldName: "multipartFile",
    // 自定义增加 http  header
    // headers: {
    //   Authorization: getToken(),
    // },
    async customUpload(file, insertFn) {
      // JS 语法
      console.log(file);
      const fileData = new FormData();
      fileData.append("multipartFile", file);
      upload(fileData).then((res) => {
        insertFn(res.data.filePath, "", "");
      });
   
      // file 即选中的文件
      // 自己实现上传，并得到图片 url alt href
      // 最后插入图片
      // insertFn(url, alt, href)
    },
    // 继续写其他配置...
   
    // 【注意】不需要修改的不用写，wangEditor 会去 merge 当前其他配置
  };
   
  export default Vue.extend({
    components: { Editor, Toolbar },
    props: {
      value: {
        type: [Number, String],
        default: undefined,
      },
      lookStatus:{
        type:Boolean,
        default:false
      }
    },
    data() {
      return {
        editor: null,
        editorContent: null,
        editorContents: null,
        html: undefined,
        toolbarConfig: {},
        editorConfig,
        mode: "default", // or 'simple'
      };
    },
    created(){
      this.html = this.value;
      console.log('this.value-------',this.value)
    },
    watch: {
      // watch监听到父组件传递过来的数据后，存到data中去，然后在页面上使用
      value(newnew, oldold) {
        this.html =  newnew
      },
      deep:true,
      immediate:true
    },
    mounted() {
      // 模拟 ajax 请求，异步渲染编辑器

    },
    beforeDestroy() {
      const editor = this.editor;
      if (editor == null) return;
      editor.destroy(); // 组件销毁时，及时销毁编辑器
    },
    methods: {
      onCreated(editor) {
        this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
        if (this.lookStatus) {
           this.editor.disable() //禁用编辑
        }
        // 
         this.toolbarConfig = {
           excludeKeys: [
               "fullScreen",
               "group-video",
               "insertImage"
           ]

       }

      },
      onChange(editor) {
        // console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
        this.editorContent = editor.getHtml();
        if (this.checkVal(this.editorContent)) {
          // console.log('999966666-------------------')
          this.$emit("change", "");
          this.$emit("update:value", "");
        } else {
          // console.log('999-------------------')
          this.$emit("update:value", this.editorContent);
          this.$emit("change", this.editorContent);
        }
        // this.$emit("change", editor.getHtml());
        const toolbar = DomEditor.getToolbar(editor)
        //  console.log("工具栏配置", toolbar.getConfig().toolbarKeys); // 工具栏配置
      },
      // 判断通知内容是否为空
      checkVal(str) {
        let num = 0,
          reg = /<p>(&nbsp;|&nbsp;\s+)+<\/p>|<p>(<br>)+<\/p>/g;
        while (num < str.length && str != "") {
          num++;
          let k = str.match(reg);
          if (k) {
            str = str.replace(k[0], "");
          }
        }
        return str == "";
      },
    },
  });
  </script>
  <style src="@wangeditor/editor/dist/css/style.css"></style>
  <style lang="scss" scoped>
  .notice {
     line-height: normal;
     table {
       border: none;
       border-collapse: collapse;
       margin-top: 25px;
     }
     table td,
     table th{
       border: 1px solid #ccc;
       padding: 3px 5px;
       min-width: 50px;
       height: 20px;
     }
     table th {
       border-right: 1px solid #ccc;
       border-bottom: 2px solid #ccc;
       text-align: center;
       background-color: #f1f1f1;
     }
     blockquote{
       display: block;
       border-left: 8px solid #d0e5f2;
       padding: 5px 10px;
       margin: 10px 0;
       line-height: 1.4;
       font-size: 100%;
       background-color: #f1f1f1;
     }
     code{
      display: inline-block;
      *display: inline;
      *zoom: 1;
      background-color: #f1f1f1;
      border-radius: 3px;
      padding: 3px 5px;
      margin: 0 3px;    
     }
     pre code {
       display: block;
     }
     ul, ol{
       margin: 10px 0 10px 20px;
     }
     pre {
      border: 1px solid #ccc;
      background-color: #f8f8f8;
      padding: 10px;
      margin: 5px 0px;
      font-size: 0.8em;
      border-radius: 3px;
     }
     .ql-editor ul li {
        list-style-type: disc;    // 解决序列li前面的.不展示问题
     }
     .ql-editor ol li {
        list-style-type: decimal;   // 解决序列li前面的数字不展示问题
     }
   }
   
  </style>